package org.grayrabbit.web.struts2;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import nl.bitwalker.useragentutils.Browser;
import nl.bitwalker.useragentutils.UserAgent;

import org.apache.struts2.ServletActionContext;
import org.grayrabbit.commons.util.logging.Logger;
import org.grayrabbit.commons.util.logging.LoggerFactory;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class SimpleActionSupport extends ActionSupport {
    private static final long     serialVersionUID = -6815712361545567993L;
    protected static final Logger LOG              = LoggerFactory
                                                       .getLogger(SimpleActionSupport.class);

    /**
     * 绕过Template,直接输出内容的简便函数. 
     */
    protected String render(String text, String contentType) {
        try {
            HttpServletResponse response = ServletActionContext.getResponse();
            response.setContentType(contentType);
            //不缓存
            response.setHeader("Pragma", "No-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            response.getWriter().write(text);
        } catch (IOException e) {
            LOG.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * 获取Application对象值
     * @param key
     * @return
     */
    protected Object getAppValue(Object key) {
        return ActionContext.getContext().getApplication().get(key);
    }

    /**
     * 获取session对象值
     * @param key
     * @return
     */
    protected Object getSessionValue(Object key) {
        return ActionContext.getContext().getSession().get(key);
    }

    /**
     * 设置session对象值
     * @param
     * @return
     */
    protected Object setSessionValue(String key, Object value) {
        return ActionContext.getContext().getSession().put(key, value);
    }

    /**
     * 删除session对象值
     * @param
     * @return
     */
    protected Object removeSessionValue(String key) {
        return ActionContext.getContext().getSession().remove(key);
    }

    /**
     * 获取getParamepters对象值
     * @param key
     * @return
     */
    protected Object getParamValue(Object key) {
        return ActionContext.getContext().getParameters().get(key);
    }

    /**
     * 获取分页信息的url地址
     * @return
     */
    public String getNoPageUrl() {
        StringBuilder sb = new StringBuilder();
        for (String key : ActionContext.getContext().getParameters().keySet()) {
            if (ignore(key))
                continue;
            sb.append(getParamStrValue(key));
        }
        return sb.toString();
    }

    private String getParamStrValue(String key) {
        StringBuilder sb = new StringBuilder();
        String[] params = (String[]) getParamValue(key);
        for (String value : params) {
            sb.append('&');
            sb.append(key);
            sb.append('=');
            sb.append(value);
        }
        return sb.toString();
    }

    private boolean ignore(String key) {
        if ("page.pageNo".equalsIgnoreCase(key)) {
            return true;
        }
        if ("page.pageSize".equalsIgnoreCase(key)) {
            return true;
        }
        if ("page.orderBy".equalsIgnoreCase(key)) {
            return true;
        }
        if ("page.order".equalsIgnoreCase(key)) {
            return true;
        }
        return false;
    }

    /**
     * 直接输出字符串.
     */
    protected String renderText(String text) {
        return render(text, "text/plain;charset=UTF-8");
    }

    /**
     * 直接输出HTML.
     */
    protected String renderHtml(String html) {
        return render(html, "text/html;charset=UTF-8");
    }

    /**
     * 直接输出json对象
     */
    protected String renderJson(String json) {
        return render(json, "application/json;charset=UTF-8");
    }

    /**
     * 直接输出XML.
     */
    protected String renderXML(String xml) {
        return render(xml, "text/xml;charset=UTF-8");
    }

    public HttpServletRequest getRequest() {
        return ServletActionContext.getRequest();
    }

    public HttpServletResponse getResponse() {
        return ServletActionContext.getResponse();
    }

    /**
     * 获取当前应用目录
     * @return
     */
    protected String getContextPath() {
        return ServletActionContext.getRequest().getContextPath();
    }

    /**
     * 根据文件夹获取服务器物理路径
     * @param path
     * @return
     * @author LS
     */
    public static String getRealPath(String path) {
        return ServletActionContext.getServletContext().getRealPath(path);
    }

    /**
     * 动态获取网站的网址 http://localhost:80/salesmng/)
     */
    protected String getServerUrl() {
        StringBuffer urlStr = new StringBuffer(ServletActionContext.getRequest().getScheme());
        urlStr.append("://");
        urlStr.append(ServletActionContext.getRequest().getServerName());
        urlStr.append(":");
        urlStr.append(ServletActionContext.getRequest().getServerPort());
        urlStr.append(ServletActionContext.getRequest().getContextPath());
        urlStr.append("/");
        return urlStr.toString();
    }

    /**
     * 获取当前URI,从应用目录开始 不包含域名
     * 
     * @return URI字符
     */
    protected String getServletPath() {
        return ServletActionContext.getRequest().getServletPath();
    }

    /**
     * 获取当前URL,整个HTTP
     * @return URL字符
     */
    protected String getCurrentUrl() {
        return ServletActionContext.getRequest().getRequestURL().toString();
    }

    /**
     * 获取浏览器
     * 
     * @return
     */
    protected String getClientBrowser() {
        try {
            UserAgent userAgent = Struts2Utils.getUserAgent();
            return userAgent.getBrowser().getName()
                   + (userAgent.getBrowser().getGroup() == Browser.IE ? "" : (" " + userAgent
                       .getBrowserVersion().getVersion()));
        } catch (Exception e) {
            LOG.error("取获客户端浏览器时有异常", e);
            return "未知";
        }
    }
    /**
     * 获取操作系统
     * 
     * @return
     */
    protected String getClientOs(){
        try {
            UserAgent userAgent = Struts2Utils.getUserAgent();
            return userAgent.getOperatingSystem().getName();
        } catch (Exception e) {
            LOG.error("取获客户端操作系统时有异常", e);
            return "未知";
        }
    }

}
